<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

global $USER, $APPLICATION;
?>
<?
$APPLICATION->SetAdditionalCSS("/online/online.css");
require_once ($_SERVER["DOCUMENT_ROOT"]."/online/Online_message.php");
echo "<pre>";


if ($_SERVER["REQUEST_METHOD"] == "POST")
{
	//echo "===============================<br>";
	//echo "this is POST<br>";
	//print_r($_REQUEST);
	//echo "===============================<br>";
}
echo "</pre>";

//////////////////////////////////
$bAuth = $USER->IsAuthorized();
$stream_id = false;
$author_id = false;

if ($bAuth)
{
	$arFilter = array("ENTITY_TYPE"=> "U", "ENTITY_ID" => $USER->GetID());
}
else
{
	$hash = $APPLICATION->get_cookie("CONSULT_USER_SID");
	$arFilter = array("ENTITY_TYPE"=> "G", "ENTITY_ID" =>$hash);
}
$obConsUser = new CConsultUser;
$dbUser = $obConsUser->GetList (array(), $arFilter);
if ($arUser = $dbUser->Fetch())
{
	$author_id = $arUser["ID"];
	$ob_stream = new COnline_stream;
	$dbStream = $ob_stream->GetList(array(), array("ENTITY_ID"=> $author_id));
	if ($arStream = $dbStream -> Fetch())
	{
		$stream_id = $arStream["ID"];
	}
}


//////////////////////////////////
if ($stream_id)
{
	$obConsMess = new COnline_message;
	$dbMess = $obConsMess->GetList(array("NUMBER" =>"ASC"), array("STREAM_ID" => $stream_id));
	$arMess = array();
	while ($mess = $dbMess->Fetch())
	{
		if (intval ($mess["REAL_USER_ID"]) > 0 && (CConsultUser::IsAdmin($mess["REAL_USER_ID"]) || CConsultUser::IsConsultTeam($mess["REAL_USER_ID"])))
		{
			$mess["IS_SUPPORT"] = "Y";
		}
		$arMess[] = $mess;
	}
	if (count($arMess) > 0)
	{
		foreach ($arMess as $message)
		{?>
			<table class="out_mess">
			<tr class="tr_head">
				<td>
					#<?=$message["NUMBER"];?>
				</td>
				<td>
					<?=$message["DATE_CREATE"]?>		
				</td>
				<td><??>
					<?echo ($message["IS_SUPPORT"] == "Y") ? "(support message)" : ""?>
				</td>
			</tr>
			<tr>
				<td colspan="3">
					<?=$message["MESSAGE"]?>			
				</td>
			</tr>
			</table>
			<?
		}
		
	}
}
else
{
	echo '<br><span class="alert">STREAM_ID not set</div>';
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && check_bitrix_sessid() && strlen ($add_post)>0)
{
	$bNeedCreateMess = false;
	
	if (!$stream_id)
	{
		//Клиент добавил первое сообщение, нужно создать STREAM_ID
		if (!is_array($arUser))
		{
			//Создаём нового пользователя
			if ($bAuth)
				$arUserAdd = array("ENTITY_TYPE"=> "U", "ENTITY_ID" => $USER->GetID());
			else
			{
				$arUserAdd = array("ENTITY_TYPE"=>"G", "ENTITY_ID"=>bitrix_sessid());
			}
			$ConsUser = new CConsultUser;
			$author_id = $ConsUser->Add($arUserAdd);
			if (!$author_id)
			{
				echo $ConsUser->LAST_ERROR;
			}
		}
		if ($author_id)
		{
			//Надо найти ответственного!!!
			$arResponsible = CGroup::GetGroupUser(1);
			$resp = $arResponsible[array_rand($arResponsible)];

			$arFields = array(
				"RESPONSIBLE_ID" => $resp,
				"ENTITY_ID" => $author_id, //АВТОР!!!!
			);
			$ob_stream = new COnline_stream;
			$stream_id = $ob_stream->Add($arFields);
			if (!$stream_id)
			{
				echo $ob_stream->METHOD."<br>".$ob_stream->LAST_ERROR;
			}
			else
			{
				$bNeedCreateMess = true;
			}
		}
	}
	if ($stream_id || $bNeedCreateMess)
	{
		global $USER;
		$ob_mess = new COnline_message;
		$arFields = array(
			"STREAM_ID"=> $stream_id,
			"OWNER_ID"=> $author_id,
			"MESSAGE"=> $_REQUEST["message"],
		);

		$messID = $ob_mess->Add($arFields);
		if ($messID)
			echo '<br><span class="note">Сообщение добавлено</span><br>';
		else
		{
			echo '<br><span class="alert">Сообщение не добавлено</span><br>';
			echo $ob_mess->METHOD."<br>".$ob_mess->LAST_ERROR;
		}
	}
	LocalRedirect($_SERVER["SCRIPT_NAME"]);
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && check_bitrix_sessid() && strlen ($new_stream)>0)
{
	$DelStreamID = $ob_stream->GetByID(intval($_REQUEST["form_stream_id"]));
	if ($DelStreamID > 0)
	{
		$ob_stream->Delete($DelStreamID);
		LocalRedirect($_SERVER["SCRIPT_NAME"]);
	}
	else
	{
		echo 'div class="alert">Удаляемый разговор не найден</div>';
	}

}
?>
<table><tr><td>
	<form method="post">
	<input type="hidden" name="form_stream_id" value="<?=(intval($stream_id)>0)? $stream_id : 0 ?>">
	<textarea name="message"></textarea><br>
	<?=bitrix_sessid_post();?>
	<input type="submit" name="add_post" value="Послать">
	<?if (intval($stream_id)>0):?>
		<input type="submit" name="new_stream" value="Начать новый разговор">
	<?endif?>
	</form>
</td></tr></table>
<?
?>
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>

